package com.sunwhite.kaikeba.utils.http;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;
import java.util.Set;

/**
 * HTTP请求工具类
 */
public class HttpClientUtil {

    private static Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);

    private static String CONNECTTIME = "1000";//请求时间限时1秒
    private static String READTIMEOUT = "10000";

    /**
     * http请求POST方式
     *
     * @param requestUrl 请求URL
     * @param params     map格式请求参数
     * @return String
     */
    public static String post(String requestUrl, Map<String, Object> params) {
        URL url;
        try {
            url = new URL(requestUrl);
            HttpURLConnection http = (HttpURLConnection) url.openConnection();
            http.setRequestMethod("POST");
            http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            http.setDoOutput(true);
            http.setDoInput(true);
            System.setProperty("sun.net.client.defaultConnectTimeout", CONNECTTIME);
            System.setProperty("sun.net.client.defaultReadTimeout", READTIMEOUT);
            http.connect();
            String parameters = "";
            if (params != null) {
                Set<String> strings = params.keySet();
                for (String key : strings) {
                    String value = params.get(key) != null ? params.get(key).toString() : "";
                    value = URLEncoder.encode(value, "UTF-8");
                    parameters += key + "=" + value + "&";
                }
                if (strings.size() > 0) {
                    parameters = parameters.substring(0, parameters.length() - 1);
                }
            }
            OutputStream os = http.getOutputStream();
            os.write(parameters.getBytes("UTF-8"));// 传入参数
            InputStream is = http.getInputStream();
            ByteArrayOutputStream jsonBytes = new ByteArrayOutputStream();
            byte[] bt = new byte[128];
            int len = 0;
            while ((len = is.read(bt)) != -1) {
                jsonBytes.write(bt, 0, len);
            }
            String result = new String(jsonBytes.toByteArray(), "UTF-8");
            is.close();
            os.flush();
            os.close();
            return result;
        } catch (Exception e) {
            logger.error("http请求错误，{}", e.getMessage());
            e.printStackTrace();
        }
        return "";
    }

    /**
     * http请求GET方式
     *
     * @param requestUrl 请求URL
     * @return String
     */
    public static String get(String requestUrl) {
        URL url;
        try {
            url = new URL(requestUrl);
            HttpURLConnection http = (HttpURLConnection) url.openConnection();
            http.setRequestMethod("GET");
            http.setDoInput(true);
            System.setProperty("sun.net.client.defaultConnectTimeout", CONNECTTIME);
            System.setProperty("sun.net.client.defaultReadTimeout", READTIMEOUT);
            http.connect();
            InputStream is = http.getInputStream();
            ByteArrayOutputStream jsonBytes = new ByteArrayOutputStream();
            byte[] bt = new byte[128];
            int len = 0;
            while ((len = is.read(bt)) != -1) {
                jsonBytes.write(bt, 0, len);
            }
            String result = new String(jsonBytes.toByteArray(), "UTF-8");
            is.close();
            return result;
        } catch (Exception e) {
            logger.error("http请求错误，{}", e.getMessage());
            e.printStackTrace();
        }
        return "";
    }

    public static Map<String,Object> doGet(String url,Map<String,String> query){

        if (!StringUtils.isEmpty(query)){
            url=url+"?";
          for (Map.Entry<String, String> parm : query.entrySet()) {
            //参数拼接
              url=url+parm.getKey()+"="+parm.getValue()+"&";
          }
            url=url.substring(0,url.length()-2);
        }
        String s = get(url);
        ObjectMapper objectMapper = new ObjectMapper();
        Map<String,Object> map=null;
        try {
             map = objectMapper.readValue(s, Map.class);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return map;
    }

}
